package com.code.google.wormon;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;

import com.code.google.wormon.base.Game;
import com.code.google.wormon.base.GameObject;

public class WormonGuy implements GameObject {

	private Rectangle bounds;
	private Image image;

	private Game game;

	private boolean moveLeft = false;
	private boolean moveRight = false;

	private boolean moveTop = false;
	private boolean moveBottom = false;

	public WormonGuy(Game game) {
		super();
		this.game = game;
		image = new ImageIcon(getClass().getClassLoader().getResource("com/code/google/wormon/resources/worm.png")).getImage();
		bounds = new Rectangle(10, 10, image.getWidth(null), image.getHeight(null));
	}

	@Override
	public void collided(GameObject other) {
	}

	@Override
	public void react(KeyEvent keyEvent) {
		if (keyEvent.getID() == KeyEvent.KEY_PRESSED) {
			if (keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
				moveLeft = true;
			} else if (keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
				moveRight = true;
			}
			if (keyEvent.getKeyCode() == KeyEvent.VK_UP) {
				moveTop = true;
			} else if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
				moveBottom = true;
			}
		} else if (keyEvent.getID() == KeyEvent.KEY_RELEASED) {
			if (keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
				moveLeft = false;
			} else if (keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
				moveRight = false;
			}
			if (keyEvent.getKeyCode() == KeyEvent.VK_UP) {
				moveTop = false;
			} else if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
				moveBottom = false;
			}
		}
	}

	@Override
	public void draw(Graphics2D g2d) {
		g2d.drawImage(image, bounds.x, bounds.y, null);
	}

	@Override
	public Rectangle getBounds() {
		return bounds;
	}

	@Override
	public void doLogic() {
		if (moveLeft) {
			walk();
		}
		if (moveRight) {
			walkBack();
		}
		if (moveTop) {
			bounds.y -= 1;
		}
		if (moveBottom) {
			bounds.y += 1;
		}
	}

	private void walkBack() {
		bounds.x += 1;
	}

	private void walk() {
		bounds.x -= 1;
	}

	public Game getGame() {
		return game;
	}

	@Override	
	public int getPosX(){
		return bounds.x;
	}
	
	@Override
	public int getPosY(){
		return bounds.y;
	}

}
